package com.ushio.capsuleservice.controller;

import com.ushio.capsuleservice.model.dto.ApiResponse;
import com.ushio.capsuleservice.model.dto.LoginRequest;
import com.ushio.capsuleservice.model.dto.RegisterRequest;
import com.ushio.capsuleservice.model.entity.User;
import com.ushio.capsuleservice.service.UserService;
import com.ushio.capsuleservice.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/api/user")
@CrossOrigin(origins = "*")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    /**
     * 用户注册
     */
    @PostMapping("/register")
    public ApiResponse<User> register(@Valid @RequestBody RegisterRequest request) {
        try {
            User user = userService.register(request);
            // 不返回密码
            user.setPassword(null);
            return ApiResponse.success("注册成功", user);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ApiResponse<Map<String, Object>> login(@Valid @RequestBody LoginRequest request) {
        try {
            String token = userService.login(request);
            User user = userService.findByUsername(request.getUsername());
            
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("user", user);
            
            return ApiResponse.success("登录成功", data);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 获取当前用户信息
     */
    @GetMapping("/profile")
    public ApiResponse<User> getProfile(HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            Long userId = jwtUtil.getUserIdFromToken(token);
            User user = userService.getById(userId);
            if (user != null) {
                user.setPassword(null); // 不返回密码
            }
            return ApiResponse.success(user);
        } catch (Exception e) {
            return ApiResponse.error("获取用户信息失败");
        }
    }
    
    /**
     * 更新用户信息
     */
    @PutMapping("/profile")
    public ApiResponse<User> updateProfile(@RequestBody User user, HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            Long userId = jwtUtil.getUserIdFromToken(token);
            User updatedUser = userService.updateUserInfo(userId, user);
            updatedUser.setPassword(null); // 不返回密码
            return ApiResponse.success("更新成功", updatedUser);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 修改密码
     */
    @PutMapping("/password")
    public ApiResponse<String> changePassword(@RequestBody Map<String, String> request, HttpServletRequest httpRequest) {
        try {
            String token = getTokenFromRequest(httpRequest);
            Long userId = jwtUtil.getUserIdFromToken(token);
            String oldPassword = request.get("oldPassword");
            String newPassword = request.get("newPassword");
            
            boolean success = userService.changePassword(userId, oldPassword, newPassword);
            if (success) {
                return ApiResponse.success("密码修改成功", null);
            } else {
                return ApiResponse.error("密码修改失败");
            }
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 从请求中获取token
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        throw new RuntimeException("未找到有效的token");
    }
}
